package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author 马迎迎
 * @Title: CartServiceImpl
 * @Package com.atguigu.gulimall.cart.service.impl
 * @Description: TODO(添加描述)
 * @date 2021年05月28日 10:38
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    ThreadPoolExecutor executor;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String CART_PREFIX = "gulimall:cart:";

    /**
     * 商品添加到购物车
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //新商品添加到购物车

        String res = (String) cartOps.get(skuId.toString());
        if (!StringUtils.isEmpty(res)) {
            //购物车有此商品 修改数量即可
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount()+num);
            cartItem.setCheck(true);
            String string = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), string);
            return cartItem;
        } else {
            CartItem cartItem = new CartItem();
            cartItem.setSkuId(skuId);
            cartItem.setCount(num);
            cartItem.setCheck(true);
            //1.远程查询当前要添加的商品详情
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //商品详情
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());
//            if (r.getCode() == 200) {
//                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
//                });
//                //商品详情
//                cartItem.setTitle(skuInfo.getSkuTitle());
//                cartItem.setImage(skuInfo.getSkuDefaultImg());
//                cartItem.setPrice(skuInfo.getPrice());
//            }
            }, executor);
            //2.远程查出skuSaleAttr
            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();
            String string = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), string);
            return cartItem;
        }
    }

    public CartItem myAddToCart(Long skuId,Integer num)throws Exception{
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if(!StringUtils.isEmpty(res)){
            //购物车已经有了，只需要增加数量
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(num+cartItem.getCount());
            cartItem.setCheck(true);
            String string = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),string);
            return cartItem;
        }else {
            CartItem cartItem = new CartItem();
            cartItem.setSkuId(skuId);
            cartItem.setCount(num);
            cartItem.setCheck(true);
            CompletableFuture<Void> getSkuInfoTask=CompletableFuture.runAsync(()->{
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setTitle(skuInfo.getSkuName());
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setPrice(skuInfo.getPrice());

            },executor);
            CompletableFuture<Void> getSkuSaleAttrValuesTask=CompletableFuture.runAsync(()->{
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            },executor);
            CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValuesTask).get();
            String string = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),string);
            return cartItem;
        }
    }
    @Override
    public CartItem getCartItemBySkuId(Long skuId) {
        String res = (String) getCartOps().get(skuId.toString());
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        return cartItem;
    }

    public CartItem myGetCartItemBySkuId(Long skuId){
        String res= (String) getCartOps().get(skuId.toString());
        CartItem cartItem = JSON.parseObject(res, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            //1.已登录
            String key = CART_PREFIX + userInfoTo.getUserId();
            //2.如果临时购物车的数据还没有进行合并[合并购物车]
            //获取临时购物车的所有购物项
            String tempCartKey=CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if(tempCartItems!=null){
                //临时购物车有数据 需要合并
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                //清空临时购物车
                clearCart(tempCartKey);
            }

            //3.获取登录后的购物车[包含合并的临时购物车和登录后的购物车数据]
            List<CartItem> cartItems = getCartItems(key);
            cart.setItems(cartItems);
        }else {
            //没登录
            String key = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItem> items = getCartItems(key);
            cart.setItems(items);
        }
        return cart;
    }

    public Cart myGetCart() throws Exception{
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            //已登录
            String key = CART_PREFIX+userInfoTo.getUserId();
            String temp_key=CART_PREFIX+userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(temp_key);
            if(tempCartItems!=null){
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(),tempCartItem.getCount());
                }
                clearCart(temp_key);
            }
            //获取登录后的购物车
            List<CartItem> cartItems = getCartItems(key);
            cart.setItems(cartItems);
        }else{
            String temp_key=CART_PREFIX+userInfoTo.getUserKey();
            //获取临时购物车所有购物项
            List<CartItem> cartItems = getCartItems(temp_key);
            cart.setItems(cartItems);
        }
        return cart;
    }
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCheck(check.intValue()==1?true:false);
        String string = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), string);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItemBySkuId(skuId);
        cartItem.setCount(num);
        String string = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), string);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }else{
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            //只返回所有被选中的购物项
            List<CartItem> collect = cartItems.stream().filter((item) -> {
                return item.getCheck();
            }).map((item)->{
                R r = productFeignService.getNewPrice(item.getSkuId());
                BigDecimal data = r.getData("data", new TypeReference<BigDecimal>() {
                });
                //TODO 更新为最新的价格
                item.setPrice(data);
                return item;
            }).collect(Collectors.toList());
            return collect;
        }

    }

    private List<CartItem> getCartItems(String cartKey){
         BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
         List<Object> values = hashOps.values();

         if(values!=null&&values.size()>0){
             List<CartItem> items = values.stream().map((obj) -> {
                 CartItem cartItem = JSON.parseObject((String) obj, CartItem.class);
                 return cartItem;
             }).collect(Collectors.toList());
             return items;
         }
        return null;
     }
    /**
     * 根据用户/临时用户id在redis数据库获取到我们要操作的购物车（数据结构是Hash）
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1.
        String cart_key = "";
        if (userInfoTo.getUserId() != null) {
            //登录了 gulimall:cart:1
            cart_key = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cart_key = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cart_key);
        return operations;
    }

    private BoundHashOperations<String,Object,Object> myGetCartOps(){
        UserInfoTo userInfoTo=CartInterceptor.threadLocal.get();
        String cart_key="";
        if(userInfoTo.getUserId()!=null){
            //用户登录了
            cart_key=CART_PREFIX+userInfoTo.getUserId();
        }else{
            cart_key=CART_PREFIX+userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cart_key);
        return operations;
    }
}
